package calvin.controller.view;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.datanucleus.util.StringUtils;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import calvin.datastore.model.RateV;
import calvin.utils.DateUtil;
import calvin.utils.RateHelper;

public class ChartController extends Controller {

    private List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    private String cp = null;

    private int count;

    private String type = null;

    @Override
    public Navigation run() throws Exception {
        cp = asString("cp");
        if (StringUtils.isEmpty(cp)) {
            cp = "USDJPY";
        }
        try {
            count = Integer.valueOf(asString("count"));
        } catch (NumberFormatException e) {
            count = 100;
        }
        type = asString("type");
        if (StringUtils.isEmpty(type)) {
            type = "5m";
        }

        List<?> list = null;
        if ("5m".equals(type)) {
            list = RateHelper.get5mRateFromStore(cp, count);
        } else if ("1h".equals(type)) {
            list = RateHelper.get1hRateFromStore(cp, count);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        sdf.setTimeZone(DateUtil.getTimeZone());
        if(list == null) {
            return forward("/error/error.jsp");
        }
        for (int i = list.size() - 1; i > -1;  i--) {
            Object o = list.get(i);
            RateV r = (RateV)o;
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("t", r.getT());
            map.put("l", r.getL());
            map.put("o", r.getO());
            map.put("c", r.getC());
            map.put("h", r.getH());
            result.add(map);
        }

        requestScope("result", result);
        requestScope("cp", cp);
        requestScope("type", type);
        return forward("chart.jsp");
    }
}
